<?php
/**
 * Login controller file.
 *
 * @author       fanlc<lingchao.fan@huatandm.com>
 * @copyright    Copyright (c) 2013,上海华探通讯技术有限公司
 * @filesource
 */
defined('IN_RCPHP') or exit('Access denied');

class loginController extends commonController
{

	/**
	 * Template variable
	 *
	 * @var array
	 */
	private $_data = array();

	/**
	 * Model object
	 *
	 * @var object
	 */
	private $_model = null;

	/**
	 * Extends base construct method.
	 *
	 * @author fanlc<lingchao.fan@huatandm.com>
	 */
	public function __construct()
	{
		parent::__construct();
		$this->_model = M('login');
	}

	/**
	 * Login page.
	 *
	 * @author fanlc<lingchao.fan@huatandm.com>
	 * @return mixed
	 */
	public function index()
	{
		// 已经登录
		if(RcCookie::is_set('user_info') === true)
		{
			list ($uid, $username, $isEnable) = explode(',', RcMcrypt::decrypt(RcCookie::get('user_info'), EMS_PUBLIC_KEY));
			$info = $this->_commonModel->getUserInfo($uid);
			if(!empty($info))
			{
				$this->redirect('/index.php?c=login&a=logout&islogout=1');
			}
		}
		$this->initMeetPage($this->_data, $this->_mid, 18);
		$this->_data['language'] = array(
			'login' => Util::_t('wap_login_login'),
			'join' => Util::_t('wap_login_join'),
		);

		$this->_data['pageTitle'] = Util::_t('wap_login_title');
		$this->_data['uri'] = !empty($_SERVER['HTTP_REFERER']) ?($_SERVER['HTTP_REFERER'] == 'http://'.$_SERVER['HTTP_HOST'].'/index.php?c=login' ? '/index.php':$_SERVER['HTTP_REFERER'])  : '/index.php';
		$this->display('loginView', $this->_data);
		unset( $this->_data);
	}

	/**
	 * Login
	 *
	 * @author fanlc<lingchao.fan@huatandm.com>
	 * @return void
	 */
	public function login()
	{
		$data = array(500);
		if(RcCheck::isAjax())
		{
			$username = trim(P('username'));
			$password = trim(P('password'));
			$data = array();
			if(empty($username))
			{
				$data = array(
					'code' => '403',
					'error' => '请输入帐户名',
				);
			}
			elseif(RcCheck::isEmail($username) === false)
			{
				$data = array(
					'code' => '403',
					'error' => '帐户名格式错误',
				);
			}
			elseif(empty($password))
			{
				$data = array(
					'code' => '403',
					'error' => '请输入密码',
				);
			}
			else
			{
				$password = substr(md5($password), 0, 16);
				//Login
				$info = $this->_model->validateLogin($username);
				if(empty($info))
				{
					$data = array(
						'code' => '403',
						'error' => '该帐号不存在',
					);
				}
				else if($password != $info['password'])
				{
					$data = array(
						'code' => '403',
						'error' => '登录名或密码不正确，请重新输入或找回密码',
					);
				}
				else
				{
					//获取用户的禁用状态 1表示禁止发言 2表示禁止访问 3表示锁定用户  4表示清空所有发言 5表示禁止创建会议
					$statusUser = $this->getUserBannedStatus($this->_uid);
					//获取IP的禁用状态 1表示禁止发言 2表示禁止访问  5表示禁止创建会议
					$statusIp = $this->getIpBannedStatus(bindec(decbin(ip2long(getIp()))));
					//当用户被禁止访问或锁定用户时EMS不允许登录
					if($statusUser == 2 || $statusUser == 3 || $statusIp == 2)
					{
						$data = array(
							'code' => '403',
							'error' => '登录失败！',
						);
					}
				}
				if(empty($data))
				{
					$data = array(
						'code' => '200',
						'error' => '登录成功',
					);

					$expire = 3600 * 12;
					$this->setUserLoginInfo($info['uid'], $expire);
				}
				else
				{
					$this->setUserLoginInfo($info['uid'], 0, $data['error']);
				}
			}
		}
		echo json_encode($data);
		exit();
	}

	/**
	 * User join
	 *
	 * @author  fanlc<lingchao.fan@huatandm.com>
	 * @return void
	 */
	public function join()
	{
		$data = array(500);
		if(RcCheck::isAjax())
		{
			$username = trim(P('username'));
			$password = trim(P('password'));
			$repassword = trim(P('repassword'));

			if(empty($username)) //用户名为空
			{
				$data = array(
					'code' => 403,
					'error' => empty($this->_lang) ? '请输入帐户名' : 'please enter username',
				);
			}
			elseif(RcCheck::isEmail($username) === false) //用户名格式不正确
			{
				$data = array(
					'code' => 403,
					'error' => empty($this->_lang) ? '帐户名格式错误' : 'username format is incorrect',
				);
			}
			elseif(empty($password)) //密码为空
			{
				$data = array(
					'code' => 403,
					'error' => empty($this->_lang) ? '请输入密码' : 'please enter password',
				);
			}
			elseif($password != $repassword)
			{
				$data = array(
					'code' => 403,
					'error' => empty($this->_lang) ? '两次输入密码不一致' : 'enter the password twice inconsistent',
				);
			}
			else
			{
				$info = $this->_model->validateLogin($username);
				if(!empty($info)) //用户名已存在
				{
					$data = array(
						'code' => 403,
						'error' => empty($this->_lang) ? '该账号已存在，请重新输入' : 'the username already exists, please re-enter',
					);
				}
				else
				{
					$joinData['username'] = $joinData['email'] = $username;
					$joinData['password'] = substr(md5($password), 0, 16);
					$joinData['regTime'] = time();
					//获取用户IP地址
					$joinData['regIp'] = bindec(decbin(ip2long(getIp())));
					$joinData['isEnable'] = 1;
					//获取用户设备
					$joinData['userAgent'] = Util::getUserAgent();

					$uid = $this->_model->createUser($joinData);
					if($uid !== false)
					{
						$data = array(
							'code' => 200,
							'error' => 'OK',
						);
						$this->sendConfirmMail($uid, $joinData['email']);
					}
				}
			}
		}

		echo json_encode($data);
		exit();
	}

	/**
	 * set password
	 *
	 * @author fanlc<lingchao.fan@huatandm.com>
	 * @return void
	 */
	public function setPassword()
	{
		$data = array(500);
		if(RcCheck::isAjax())
		{
			$oldPwd = trim(P('password_old'));
			$newPwd = trim(P('password_new'));
			$reNewPwd = trim(P('password_new2'));
			if(empty($oldPwd) || empty($newPwd) || empty($reNewPwd))
			{
				$data = array(
					'code' => 403,
					'error' => '密码不能为空'
				);
			}
			elseif(strlen($newPwd) < 6 || strlen($newPwd) > 16)
			{
				$data = array(
					'code' => 403,
					'error' => '密码长度错误'
				);
			}
			elseif($newPwd !== $reNewPwd)
			{
				$data = array(
					'code' => 403,
					'error' => '两次密码不一致'
				);
			}
			elseif($oldPwd === $newPwd)
			{
				$data = array(
					'code' => 403,
					'error' => '新密码不能与现用密码相同'
				);
			}
			else
			{
				$oldPwd = substr(md5($oldPwd), 0, 16);
				$check = $this->_model->checkUserPassword($this->_uid, $oldPwd);
				if(false === $check)
				{
					$data = array(
						'code' => 403,
						'error' => '现有密码错误'
					);
				}
				else
				{
					$info['password'] = substr(md5(md5($newPwd)), 0, 16);

					$result = $this->_commonModel->setUserInfo($info, $this->_uid);
					if($result !== false)
					{
						$data = array(
							'code' => 200,
							'error' => 'OK'
						);
					}
					else
					{
						$data = array(
							'code' => 403,
							'error' => '密码修改失败'
						);
					}
				}
			}
		}
		echo json_encode($data);
		exit();
	}

	/**
	 * Set login info
	 * empty message for login success
	 *
	 * @author fanlc<lingchao.fan@huatandm.com>
	 * @param int    $uid
	 * @param int    $expire
	 * @param string $message
	 */
	private function setUserLoginInfo($uid, $expire = 3600, $message = '')
	{
		$logData['loginTime'] = time();
		$logData['loginIp'] = bindec(decbin(ip2long(getIp())));
		$userInfo = $this->_commonModel->getUserInfo($uid);

		if(empty($message))
		{
			//set login info
			$this->_commonModel->setUserInfo($logData, $userInfo['uid']);

			$user_info = $userInfo['uid'] . ',' . $userInfo['username'] . ',' . $userInfo['isEnable'] . ',' . $userInfo['name'];
			$user_info = RcMcrypt::encrypt($user_info, EMS_PUBLIC_KEY);
			RcCookie::set('user_info', $user_info, time() + intval($expire), '/', '.pujiangforum.org');
			RcCookie::set('uid', $userInfo['uid'], time() + intval($expire), '/', '.pujiangforum.org');

			$message = '登录成功';
		}
		//Add login log info.
		$logData['uid'] = intval($userInfo['uid']);
		$logData['message'] = $message . ':' . $userInfo['username'];
		$this->_model->setUserLoginLogInfo($logData);
	}

	/**
	 * Send validate email.
	 *
	 * @author fanlc<lingchao.fan@huatandm.com>
	 * @param int    $uid
	 * @param string $email
	 * @return bool
	 */
	private function sendConfirmMail($uid, $email)
	{
		if(empty($uid) || empty($email))
		{
			return false;
		}
		$confirm_link = EMS_HTTP_HOST . '/index.php?c=join&a=regConfirmation&confirmation_token=';
		//$uid+逗号+$email  base64编码
		$confirm_link .= base64_encode($uid . ',' . $email);
		//存储用户邮激活码的生成时间
		$redis = load_class('RcRedis', 'libraries');
		$redis->hset('confirmCode', $uid, time());

		if($redis->hGet('confirmCode', $uid))
		{
			$body = '<b>亲爱的 ' . $email . '：<b><br/><br/>

					您好！欢迎您注册成为有氧会议网会员，请点击下面的地址激活你在有氧会议网的帐号：（激活后您可以免费创建5次会议哦）<br/><br/>

					<a href="' . $confirm_link . '" target="_blank">' . $confirm_link . '</a><br/><br/>

					如果以上链接无法点击，请将上面的地址复制到你的浏览器(如IE)的地址栏进入有氧会议网也可激活。<br/>
					为了保障您帐号的安全性，请在 12小时内完成激活，此链接将在您激活过一次后失效！<br/><br/>
					--<a href="http://www.o2oevent.com/" target="_blank">有氧会议网</a><br/>
					' . date("Y-m-d H:i") . '<br/>
					==========================================================<br/>
					此邮件为系统自动发出的邮件，请勿直接回复。';

			return Util::sendEmail($email, "[有氧会议网]激活您的帐号", $body);
		}

		return false;
	}

	/**
	 * Log out.
	 *
	 * @author fanlc<lingchao.fan@huatandm.com>
	 * @return void
	 */
	public function logout()
	{
		$_uid = RcCookie::get('uid');
		$islogout = G('islogout');
		if(!empty($_uid) && $islogout != 1)
		{
			showConfirm('确定要退出登录？', '/index.php?c=login&a=logout&islogout=1');
		}

		RcCookie::delete(array(
							  'user_info',
							  'uid',
							  'code_info'
						 ), '/', '.pujiangforum.org');

		$this->redirect('/index.php');
	}
}
